import os
import sys
from flask import Flask, jsonify
from gevent import pywsgi, monkey
import traceback
import time
import json
# 导入genvent猴子补丁， 实现并发操作
from project.institution import unit_web

monkey.patch_all()

app = Flask(__name__)


@app.route('/institution/query/<t_id>')
def inst_query(t_id):

    try:
        jsn = unit_web.do(t_id)
        # 成功信息
        ts = time.strftime("%Y-%m-%d %H:%M", time.localtime())
        f = open('./conf/institution/query/xx.txt', 'a+')
        f.write('查询记录：' + '\t' + ts + '\n')
        f.close()
        # 存放图片文件夹
        path_file = 'E:/PycharmProjects/pythonProject/webapi/database/images'
        # 获取文件夹下所有文件名称（列表）
        ls = os.listdir(path_file)
        for i in ls:
            # 单个图片路径组装
            f_path = os.path.join(path_file, i)
            # 删除文件
            os.remove(f_path)

        # 查询错误信息返回
        if str((json.loads(jsn)['name'])) == 'none':
            return jsonify({"information": "false"})
        else:
            # 成功信息
            ts = time.strftime("%Y-%m-%d %H:%M", time.localtime())
            f = open('./conf/institution/query/success.txt', 'a+')
            f.write('查询记录：' + '\t' + ts + '\t' + str((json.loads(jsn)['name'])) + '\n')
            f.close()

            # 返回json数据
            return jsonify(json.loads(jsn))

    except Exception as exception:

        # 杀死进程
        os.system('taskkill /im chromedriver.exe /F')
        os.system('taskkill /im chrome.exe /F')

        ts = time.strftime("%Y-%m-%d %H:%M", time.localtime())
        # 详细错误
        f = open('./conf/institution/query/log.txt', 'a+')
        f.write('错误日志：' + '\t' + ts + '\n' + str(exception) + '\n' + traceback.format_exc() + '\n')
        f.write("错误查询：" + t_id + '\n')
        f.close()
        return jsonify({"information": "false"})

@app.route('/test/<t_id>')
def test(t_id):
    os.startfile(r'E:\pp\chrome.lnk')
    return t_id

def servers():
    f = open('log.txt', 'a+')
    f.write('asdasdasdasxxxxxxxxx')
    f.write("\n")
    f.close()
    app.config['JSON_AS_ASCII'] = False
    server = pywsgi.WSGIServer(('0.0.0.0', 50009), app)
    server.serve_forever()


if __name__ == '__main__':
    app.config['JSON_AS_ASCII'] = False
    server = pywsgi.WSGIServer(('0.0.0.0', 50009), app)
    server.serve_forever()



